package com.greensam.pixelengine.facade.impl;

import com.greensam.pixelengine.exception.BusinessException;
import com.greensam.pixelengine.facade.FileFacadeService;
import com.greensam.pixelengine.manager.CosManager;
import com.greensam.pixelengine.pojo.emuns.ErrorCodeEnum;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * @author Macro_Ray
 * @since 2025/7/1 17:56
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FileFacadeServiceImpl implements FileFacadeService {

    private final CosManager cosManager;

    @Override
    public String testUploadFile(MultipartFile multipartFile) {
        // 文件目录
        String originalFilename = multipartFile.getOriginalFilename();
        String filePath = String.format("test/%s", originalFilename);

        File file = null;
        try {
            file = File.createTempFile(filePath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filePath, file);
            // 返回可访问地址
            return filePath;
        } catch (Exception e) {
            log.error("上传文件失败, filePath:{}", filePath, e);
            throw new BusinessException(ErrorCodeEnum.FileUploadError);
        } finally {
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("删除临时文件失败, filePath:{}", filePath);
                }
            }
        }
    }

    @Override
    public Void testDownloadFile(HttpServletResponse response, String filePath) {
        // cos对象输入流
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            cosObjectInput = cosObject.getObjectContent();
            // 处理下载到的流
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            // 输出流写入响应
            response.getOutputStream().write(bytes);
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("下载文件失败, filePath:{}", filePath, e);
            throw new BusinessException(ErrorCodeEnum.FileDownloadError);
        } finally {
            if (cosObjectInput != null) {
                // 释放流
                cosObjectInput.release();
            }
        }
        return null;
    }
}
